package com.supercell.misc.concurrent;

import com.supercell.misc.data.TCPConnectionStatus;
import com.supercell.service.DataManipulationService;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**
 * Created by WUJO2 on 7/15/2016.
 */
public class TCPClientConnectionThread implements Runnable {
    private Socket clientSocket;
    private DataManipulationService dataManipulationService;
    private List<Socket> clientSockets;
    private TCPConnectionStatus tcpConnectionStatus;
    private List<TCPConnectionStatus> tcpConnectionStatusList;
    private List<Thread> connectionThreadList;

    public TCPClientConnectionThread(
            Socket clientSocket,
            DataManipulationService dataManipulationService,
            List<Socket> clientSockets,
            TCPConnectionStatus tcpConnectionStatus,
            List<TCPConnectionStatus> tcpConnectionStatusList,
            List<Thread> connectionThreadList) {
        this.clientSocket = clientSocket;
        this.dataManipulationService = dataManipulationService;
        this.clientSockets = clientSockets;
        this.tcpConnectionStatus = tcpConnectionStatus;
        this.tcpConnectionStatusList = tcpConnectionStatusList;
        this.connectionThreadList = connectionThreadList;
    }

    @Override
    public void run() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())), true);
            String command;
            String[] results;
            while ((command = bufferedReader.readLine()) != null) {
                results = dataManipulationService.executeCommand(command);
                for (String result : results) {
                    printWriter.println(result);
                }
            }
        } catch (Exception ignored) {
        } finally {
            tcpConnectionStatusList.remove(tcpConnectionStatus);
            clientSockets.remove(clientSocket);
            connectionThreadList.remove(Thread.currentThread());
        }
    }
}
